<?php

$is_debug = get_input('debug', FALSE);

$email = get_input('email');
$username = get_input('username');
$password = get_input('password');
$firstname = get_input('first_name');
$lastname = get_input('last_name');
$avatar_url = get_input('avatar_url');
$fb_id = get_input('facebook_id');
$timestamp = get_input('timestamp');

$client_id = get_input('client_id');

$signature = get_input('signature');

/*
 * NSString * sourceString = [NSString stringWithFormat:@"%@,%@,%@,%@,%@,%@,%f",
  fbEmail,
  fbUsername,
  fbFirstName,
  fbLastName,
  fbAvatarUrl,
  fbUid,
  currentTimeStamp];
 */

$base_string =
        sprintf(
        "%s,%s,%s,%s,%s,%s,%f", $email, $username, $firstname, $lastname, $avatar_url, $fb_id, $timestamp
);

$hmac = compute_hash($base_string, REGISTER);

if ($hmac != $signature) {
    $result = export_result(400, 'Cannot verify request');
} else {
    $result = export_result(200, '');
    $userid = get_user_id_by_facebook($fb_id);
    if (!$userid) {
        $facebookAccounts = greengar_get_facebook($fb_id, ELGG_ENTITIES_ANY_VALUE);
        if ($facebookAccounts && $facebookAccounts[0]) {
            $facebookAccount = $facebookAccounts[0];
            $userid = $facebookAccount->owner_guid;
            // $userEntity = get_user($userid);
        }
    }
    if ($userid) {
//        echo $userid;
        $userEntity = get_user($userid);
//        print_r($userEntity);
        if ($userEntity) {
//            echo 2;
            login($userEntity);
            $oauth = oauth2_get_server();
            $result['result'] = $oauth->directlyGrantToken($client_id);
            if ($is_debug === "1") {
                $result['result']['expires_in'] = 10;
                $result['result']['debug_mode'] = $is_debug;
            }
        }
    } else {
//        echo 3;
        $userid = get_user_id_by_email($email);
        if ($userid) {
            $userEntity = get_user($userid);
        } else {
            $userEntity = get_user_by_email($email);
            if ($userEntity && is_array($userEntity)) {
                $userEntity = array_shift($userEntity);
            }
        }
        if ($userEntity) {
            login($userEntity);
            add_facebook_account(get_loggedin_userid(), $lastname, $fb_id, $email, $firstname, $firstname, $lastname, $avatar_url);
            // add_email(get_loggedin_userid(), $email);
            $oauth = oauth2_get_server();
            $result['result'] = $oauth->directlyGrantToken($client_id);
        } else {
            include(dirname(__FILE__) . '/register.php');
        }
    }
}

echo json_encode($result);
?>